<?php
/**
 * Created by PhpStorm.
 * User: liyang
 * Date: 2017/12/5  Time: 上午11:43
 * Description:获取用户 私募预约 信息
 */

use Service\ConsulationService;

class ConsultationController extends BaseController
{
    private $rules = [
        'fundId' => 'required|int'
    ];

    public function listAction()
    {
        $uid = $this->header['uid'];//用户ID

        if (empty($uid)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $info = UserVerifaceRecordModel::select('id')->where('uid', $uid)->get();

        if ($info->isEmpty()) {
            $this->callback(['list' => []], APP_REQUEST_SUCCESS, '没有预约数据');
            return;
        }
        $data = ConsulationService::getInstance()->getConsulationData($info);
        if(isset($data['datetime'])) {
            array_multisort($data['datetime'], SORT_DESC, $data['list']);
            $fundData = FundModel::select('id', 'risk_rank')->whereIn('id', $data['pid'])->get();
            if(!$fundData->isEmpty()) {
                $idByRiskRank = array_column($fundData->toArray(), 'risk_rank', 'id');
                foreach ($data['list'] as $k=>$v) {
                    if(isset($idByRiskRank[$v['pid']])) {
                        $data['list'][$k]['risk_rank'] = $idByRiskRank[$v['pid']];
                    }
                }
                $data['list'] = FundModel::classifyList($data['list'],$uid);
            }
            unset($data['datetime'],$data['pid']);
        }
        $this->callback($data);
    }

    public function facephotocheckAction()
    {
        $uid = $this->header['uid'];//用户ID

        if (empty($uid)) {
            $this->callback('', MISS_REQUEST_PARAMS, '缺少参数,参数为空');
        }

        $data = [
            'photo' => parse_url($this->getRequest()->getParam('photo'), PHP_URL_PATH),
            'fund_id' => $this->getRequest()->getParam('fund_id'),
        ];
        $rules = [
            'photo'=>'required',
            'fund_id'=>'required',
        ];
        $validator = \Rester\Validator::getInstance()->make($data, $rules);
        if ($validator->fails()) {
            $this->callback([], '0400', '参数错误');
            return;
        }

        $res = \MS\Minsh::doFaceCheck($uid, $data['fund_id'], getUploadDir() . $data['photo'], $data['photo']);
        if (is_string($res)) {
            $this->callback(['status' => -1], '0000', $res);

            return;
        }
        $return['status'] = $res;

        $commonconf = getCommonConfig('h5_baseurl');
        $fundDetail = FundModel::query()->find($data['fund_id']);
        if ($fundDetail['risk_rank'] == 5) {
            $return['alert_url'] = urlencode($commonconf.'/fund/galert');
            $return['alert_title'] = '高风险产品特别风险揭示';
        } else {
            $return['alert_url'] = urlencode($commonconf.'/fund/dalert');
            $return['alert_title'] = '风险揭示书';
        }

        $this->callback($return);
    }

    public function createAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators(['fundId' => 'required'], $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        $private = UserPrivateModel::findByUidAndPid($uId, $fundId);
        if (!$private || !$private->isOk()) {
            $this->callback([], '0400', '请先进行人脸识别');
            return;
        }
        $fund = FundModel::query()->find($fundId);
        $user = UserModel::query()->find($uId);
        $record = UserVerifaceRecordModel::query()
            ->where(['uid' => $uId, 'pid' => $fundId, 'auth_result' => 3])
            ->orderBy('id', 'DESC')
            ->first();

        /** @var UserMSModel $ms */
        $ms = UserMSModel::query()->where(['user_id' => $uId])->first();
        if (!$ms->isOk()) {
            $this->callback([], '0400', '请上传身份证照片');
            return;
        }
        if (($check = FundModel::validConsultStatus($fundId)) !== true) {
            $this->callback([], '0400', $check);
            return;
        }

        $data = array(
            'pid' => $fundId,
            'rid' => $record->id,
            'phone' => $user['cellphone'],
            'user_type' => $user['type'],
            'title' => $fund['fund_name'],
            'img_path_front'=> $ms['img_path_front'],
            'img_path_reverse'=> $ms['img_path_reverse'],
            'ctime' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
        );

        if($user['type'] == UserModel::USER_TYPE_PERSON){
            $data['name'] = $user['username'];
            $data['card_id'] = $user['identity_id'];
        }elseif($user['type'] == UserModel::USER_TYPE_ORG){
            $data['name'] = $user['organization_name'];
            $data['card_id'] = $user['business_license_number'];
        }

        $con = new ConsultationModel();
        $con->fill($data);
        if ($con->save()) {
            $this->callback([], '0000', '预约成功');
            return;
        }

        $this->callback([], '0400', '预约失败');
        return;
    }

    public function redophotoAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators(['fundId' => 'required'], $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }

        UserPrivateModel::query()->where(['uid' => $uId, 'pid' => $fundId, 'private_reserve_status' => 3])
            ->update(['private_reserve_status' => 1]);
        UserVerifaceRecordModel::query()->where(['uid' => $uId, 'pid' => $fundId, 'auth_result' => 2])
            ->update(['auth_result' => 1]);
        $this->callback();
    }

    // 预约风险揭示书提交接口
    public function riskacceptAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $accept = $this->getRequest()->getParam('accept');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId, 'accept' => $accept];
        $rules = [
            'fundId' => 'required|int',
            'accept' => 'required|int|min:0|max:1',
        ];
        if (!Rester\Validator::validators($rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }

        $private = UserPrivateModel::findByUidAndPid($uId, $fundId);
        if ($private) {
            $private->accept($accept);
        }

        $this->callback([]);
    }

    // 预约风险等级提示
    public function riskshowAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        //判断该风险值为高风险还是低风险
        $fundDetail = FundModel::where("id", $fundId)->get(['id','risk_rank'])->first();

        $data['fund_risk_level'] = getProductRiskDescription($fundDetail['risk_rank']);

        $score = EvaluationModel::select('evaluation_score')->where('uid', $uId)->first();
        $userlevel = \Service\UserService::getInstance()->getGrade($score['evaluation_score']);
        $data['user_risk_level'] = getUserRiskDescription($userlevel['grade_int']);

        $this->callback($data);
    }

    public function facecheckcntAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }

        $used = UserVerifaceRecordModel::getUsedCnt($uId, $fundId);

        $this->callback(['total' => 20, 'used' => $used]);
    }

    public function precreateAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        $fund = FundModel::query()->find($fundId);
        $user = UserModel::query()->find($uId);

        $data = [
            "fundname" => $fund->fund_name,
            "username" => $user->username,
            "idnum" => $user->identity_id,
            "phone" => $user->cellphone,
            'orgtype' => 0
        ];
        if ($user->type == 2) {
            $data = [
                "fundname" => $fund->fund_name,
                "username" => $user->organization_name,
                "idnum" => $user->business_license_number,
                "phone" => $user->cellphone,
            ];
            $orgInfo = UserOrgInfoModel::query()->where(['u_id' => $uId])->first();
            $data['orgtype'] = $orgInfo->org_type;
        }

        $this->callback($data);
    }

    // 预约人工审核通过/不通过的 通知
    public function passedAction()
    {
        $uId = $this->header['uid'];
        while (true) {
            /** @var UserVerifaceRecordModel $record */
            $record = UserVerifaceRecordModel::query()
                ->where(['uid' => $uId, 'manual_pass' => 1, 'show_done' => 0])
                ->orderBy('update_time', 'ASC')->first();
            if ($record) {
                $record->show_done = 1;
                $record->save();

                if ($record->hasManyConsultation()->get(['id'])->isEmpty()) {
                    $fund = FundModel::query()->find($record->pid);
                    $this->callback([
                        'has_record' => 1,
                        'fund_id' => $record->pid,
                        'fund_name' => $fund->fund_name,
                        'status' => $record->auth_result == 3 ? 1 : 0,
                        'img' => getUploadHost() . $record->photo_path,
                    ]);

                    return;
                }
            } else {
                $this->callback(['has_record' => 0]);
            }
        }
    }
}
